热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

这一点|主文_fabricSDKgo初探

篇首语:本文由编程笔记#小编为大家整理,主要介绍了fabric-SDK-go初探相关的知识,希望对你有一定的参考价值。1.环境安装本教程不会

篇首语:本文由编程笔记#小编为大家整理,主要介绍了fabric-SDK-go初探相关的知识,希望对你有一定的参考价值。



1. 环境安装

本教程不会详细解释 Hyperledger Fabric ,可访问其官方文档,

本文参照CHAINHERO,在Mac OS上实践,Hyperledger Fabric 框架与 Mac OS X、Windows 和其他 Linux 发行版兼容。

环境安装可参考fabric2.x环境搭建
请确保安装好了docker,go,git等环境


2.打造咱们的第一个区块链网络

为了docker构建区块链网络,我们将使用构建将处理不同角色的虚拟计算机。Hyperledger Fabric 需要大量证书来确保整个端到端流程(TSL、身份验证、签名块……)的加密。这些文件的创建需要一点时间,为了直接解决问题的核心,本文参考的教程已经fixtures在此存储库的文件夹中为准备好了所有这些。

按照我们的存储库命名,src在您的文件夹中创建一个新目录GOPATH:

mkdir -p $GOPATH/src/github.com/chainHero/heroes-service && \\
cd $GOPATH/src/github.com/chainHero/heroes-service

要获取fixtures文件夹,您可以遵循此命令行,它将安装并使用 subversion 从该存储库中获取文件夹。或者从 Github下载zip 文件并仅提取fixtures文件夹。

brew install subversion
cd $GOPATH/src/github.com/chainHero/heroes-service
svn checkout https://github.com/chainHero/heroes-service/branches/v1.1.0/fixtures
rm -rf fixtures/.svn

注:如果是Linux

apt -y subversion && \\
cd $GOPATH/src/github.com/chainHero/heroes-service && \\
svn checkout https://github.com/chainHero/heroes-service/branches/v1.1.0/fixtures &&
rm -rf fixtures/.svn

为了检查网络是否工作,我们将使用docker-compose同时启动或停止所有容器。进入fixtures文件夹,然后运行:

cd $GOPATH/src/github.com/chainHero/heroes-service/fixtures && \\
docker-compose up -d

此时能看到fabric网络已经启动

打开一个新终端运行:
docker ps

可以看到:两个对等节点,一个排序节点和一个 CA 容器。您已经成功地创建了一个新网络,可以与 SDK 一起使用。要停止网络返回上一个终端,按下Ctrl+C并等待所有容器停止。


  • 提示:当网络停止时,所有使用的容器仍然可以访问。例如,这对于检查日志非常有用。您可以使用docker ps -a. 为了清理这些容器,您需要删除它们,docker rm $(docker ps -aq)或者如果您使用了一个docker-compose文件,请转到该文件所在的位置并运行docker-compose down.

  • 提示:您可以docker-compose在后台运行该命令以保持提示。要做到这一点,使用参数-d,像这样:docker-compose up -d。要停止容器,请在所在的同一文件夹中运行docker-compose.yaml命令:(docker-compose stop或docker-compose down在所有容器停止后进行清理)。


3.使用Fabric SDK Go


3.1 配置文件

我们的应用程序需要很多参数,尤其是 Fabric 组件的地址来进行通信。我们将把所有东西都放在一个新的配置文件中,Fabric SDK Go 配置和我们的自定义参数。目前,我们只会尝试使 Fabric SDK Go 使用默认链码:

cd $GOPATH/src/github.com/chainHero/heroes-service && \\
vi config.yaml

name: "heroes-service-network"
#
# Schema version of the content. Used by the SDK to apply the corresponding parsing rules.
#
version: 1.0.0
#
# The client section used by GO SDK.
#
client:
# Which organization does this application instance belong to? The value must be the name of an org
# defined under "organizations"
organization: org1
logging:
level: info
# Global configuration for peer, event service and orderer timeouts
# if this this section is omitted, then default values will be used (same values as below)
# peer:
# timeout:
# connection: 10s
# response: 180s
# discovery:
# # Expiry period for discovery service greylist filter
# # The channel client will greylist peers that are found to be offline
# # to prevent re-selecting them in subsequent retries.
# # This interval will define how long a peer is greylisted
# greylistExpiry: 10s
# eventService:
# # Event service type (optional). If not specified then the type is automatically
# # determined from channel capabilities.
# type: (deliver|eventhub)
# the below timeouts are commented out to use the default values that are found in
# "pkg/fab/endpointconfig.go"
# the client is free to override the default values by uncommenting and resetting
# the values as they see fit in their config file
# timeout:
# connection: 15s
# registrationResponse: 15s
# orderer:
# timeout:
# connection: 15s
# response: 15s
# global:
# timeout:
# query: 180s
# execute: 180s
# resmgmt: 180s
# cache:
# connectionIdle: 30s
# eventServiceIdle: 2m
# channelConfig: 30m
# channelMembership: 30s
# discovery: 10s
# selection: 10m
# Root of the MSP directories with keys and certs.
cryptoconfig:
path: $GOPATH/src/github.com/chainHero/heroes-service/fixtures/crypto-config
# Some SDKs support pluggable KV stores, the properties under "credentialStore"
# are implementation specific
credentialStore:
path: /tmp/heroes-service-store
# [Optional]. Specific to the CryptoSuite implementation used by GO SDK. Software-based implementations
# requiring a key store. PKCS#11 based implementations does not.
cryptoStore:
path: /tmp/heroes-service-msp
# BCCSP config for the client. Used by GO SDK.
BCCSP:
security:
enabled: true
default:
provider: "SW"
hashAlgorithm: "SHA2"
softVerify: true
level: 256
tlsCerts:
# [Optional]. Use system certificate pool when connecting to peers, orderers (for negotiating TLS) Default: false
systemCertPool: false
# [Optional]. Client key and cert for TLS handshake with peers and orderers
client:
keyfile:
certfile:
#
# [Optional]. But most apps would have this section so that channel objects can be constructed
# based on the content below. If an app is creating channels, then it likely will not need this
# section.
#
channels:
# name of the channel
chainhero:
# Required. list of orderers designated by the application to use for transactions on this
# channel. This list can be a result of access control ("org1" can only access "ordererA"), or
# operational decisions to share loads from applications among the orderers. The values must
# be "names" of orgs defined under "organizations/peers"
# deprecated: not recommended, to override any orderer configuration items, entity matchers should be used.
# orderers:
# - orderer.example.com
# Required. list of peers from participating orgs
peers:
peer0.org1.hf.chainhero.io:
# [Optional]. will this peer be sent transaction proposals for endorsement? The peer must
# have the chaincode installed. The app can also use this property to decide which peers
# to send the chaincode install request. Default: true
endorsingPeer: true
# [Optional]. will this peer be sent query proposals? The peer must have the chaincode
# installed. The app can also use this property to decide which peers to send the
# chaincode install request. Default: true
chaincodeQuery: true
# [Optional]. will this peer be sent query proposals that do not require chaincodes, like
# queryBlock(), queryTransaction(), etc. Default: true
ledgerQuery: true
# [Optional]. will this peer be the target of the SDK's listener registration? All peers can
# produce events but the app typically only needs to connect to one to listen to events.
# Default: true
eventSource: true
peer1.org1.hf.chainhero.io:
policies:
#[Optional] options for retrieving channel configuration blocks
queryChannelConfig:
#[Optional] min number of success responses (from targets/peers)
minResponses: 1
#[Optional] channel config will be retrieved for these number of random targets
maxTargets: 1
#[Optional] retry options for query config block
retryOpts:
#[Optional] number of retry attempts
attempts: 5
#[Optional] the back off interval for the first retry attempt
initialBackoff: 500ms
#[Optional] the maximum back off interval for any retry attempt
maxBackoff: 5s
#[Optional] he factor by which the initial back off period is exponentially incremented
backoffFactor: 2.0
#
# list of participating organizations in this network
#
organizations:
org1:
mspid: org1.hf.chainhero.io
cryptoPath: peerOrganizations/org1.hf.chainhero.io/users/userName@org1.hf.chainhero.io/msp
peers:
- peer0.org1.hf.chainhero.io
- peer1.org1.hf.chainhero.io
# [Optional]. Certificate Authorities issue certificates for identification purposes in a Fabric based
# network. Typically certificates provisioning is done in a separate process outside of the
# runtime network. Fabric-CA is a special certificate authority that provides a REST APIs for
# dynamic certificate management (enroll, revoke, re-enroll). The following section is only for
# Fabric-CA servers.
certificateAuthorities:
- ca.org1.hf.chainhero.io
#
# List of orderers to send transaction and channel create/update requests to. For the time
# being only one orderer is needed. If more than one is defined, which one get used by the
# SDK is implementation specific. Consult each SDK's documentation for its handling of orderers.
#
orderers:
orderer.hf.chainhero.io:
url: localhost:7050
# these are standard properties defined by the gRPC library
# they will be passed in as-is to gRPC client constructor
grpcOptions:
ssl-target-name-override: orderer.hf.chainhero.io
# These parameters should be set in coordination with the keepalive policy on the server,
# as incompatible settings can result in closing of connection.
# When duration of the 'keep-alive-time' is set to 0 or less the keep alive client parameters are disabled
keep-alive-time: 0s
keep-alive-timeout: 20s
keep-alive-permit: false
fail-fast: false
# allow-insecure will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
allow-insecure: false
tlsCACerts:
# Certificate location absolute path
path: $GOPATH/src/github.com/chainHero/heroes-service/fixtures/crypto-config/ordererOrganizations/hf.chainhero.io/tlsca/tlsca.hf.chainhero.io-cert.pem
#
# List of peers to send various requests to, including endorsement, query
# and event listener registration.
#
peers:
peer0.org1.hf.chainhero.io:
# this URL is used to send endorsement and query requests
url: localhost:7051
# eventUrl is only needed when using eventhub (default is delivery service)
eventUrl: localhost:7053
grpcOptions:
ssl-target-name-override: peer0.org1.hf.chainhero.io
# These parameters should be set in coordination with the keepalive policy on the server,
# as incompatible settings can result in closing of connection.
# When duration of the 'keep-alive-time' is set to 0 or less the keep alive client parameters are disabled
keep-alive-time: 0s
keep-alive-timeout: 20s
keep-alive-permit: false
fail-fast: false
# allow-insecure will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
allow-insecure: false
tlsCACerts:
# Certificate location absolute path
path: $GOPATH/src/github.com/chainHero/heroes-service/fixtures/crypto-config/peerOrganizations/org1.hf.chainhero.io/tlsca/tlsca.org1.hf.chainhero.io-cert.pem
peer1.org1.hf.chainhero.io:
# this URL is used to send endorsement and query requests
url: localhost:8051
# eventUrl is only needed when using eventhub (default is delivery service)
eventUrl: localhost:8053
grpcOptions:
ssl-target-name-override: peer1.org1.hf.chainhero.io
# These parameters should be set in coordination with the keepalive policy on the server,
# as incompatible settings can result in closing of connection.
# When duration of the 'keep-alive-time' is set to 0 or less the keep alive client parameters are disabled
keep-alive-time: 0s
keep-alive-timeout: 20s
keep-alive-permit: false
fail-fast: false
# allow-insecure will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
allow-insecure: false
tlsCACerts:
# Certificate location absolute path
path: $GOPATH/src/github.com/chainHero/heroes-service/fixtures/crypto-config/peerOrganizations/org1.hf.chainhero.io/tlsca/tlsca.org1.hf.chainhero.io-cert.pem
#
# Fabric-CA is a special kind of Certificate Authority provided by Hyperledger Fabric which allows
# certificate management to be done via REST APIs. Application may choose to use a standard
# Certificate Authority instead of Fabric-CA, in which case this section would not be specified.
#
certificateAuthorities:
ca.org1.hf.chainhero.io:
url: http://localhost:7054
# Fabric-CA supports dynamic user enrollment via REST APIs. A "root" user, a.k.a registrar, is
# needed to enroll and invoke new users.
httpOptions:
verify: false
registrar:
enrollId: admin
enrollSecret: adminpw
# [Optional] The optional name of the CA.
caName: ca.org1.hf.chainhero.io
tlsCACerts:
# Certificate location absolute path
path: $GOPATH/src/github.com/chainHero/heroes-service/fixtures/crypto-config/peerOrganizations/org1.hf.chainhero.io/ca/ca.org1.hf.chainhero.io-cert.pem
entityMatchers:
peer:
- pattern: (\\w*)peer0.org1.hf.chainhero.io(\\w*)
urlSubstitutionExp: localhost:7051
eventUrlSubstitutionExp: localhost:7053
sslTargetOverrideUrlSubstitutionExp: peer0.org1.hf.chainhero.io
mappedHost: peer0.org1.hf.chainhero.io
- pattern: (\\w*)peer1.org1.hf.chainhero.io(\\w*)
urlSubstitutionExp: localhost:8051
eventUrlSubstitutionExp: localhost:8053
sslTargetOverrideUrlSubstitutionExp: peer1.org1.hf.chainhero.io
mappedHost: peer1.org1.hf.chainhero.io
orderer:
- pattern: (\\w*)orderer.hf.chainhero.io(\\w*)
urlSubstitutionExp: localhost:7050
sslTargetOverrideUrlSubstitutionExp: orderer.hf.chainhero.io
mappedHost: orderer.hf.chainhero.io
certificateAuthorities:
- pattern: (\\w*)ca.org1.hf.chainhero.io(\\w*)
urlSubstitutionExp: http://localhost:7054
mappedHost: ca.org1.hf.chainhero.io

配置文件也可以在这里找到: config.yaml


3.2初始化

我们添加一个名为的新文件夹blockchain,该文件夹将包含与网络通信的整个接口。我们将仅在此文件夹中看到 Fabric SDK Go。

mkdir $GOPATH/src/github.com/chainHero/heroes-service/blockchain

现在,我们添加一个名为的新 go 文件setup.go:

vi $GOPATH/src/github.com/chainHero/heroes-service/blockchain/setup.go

package blockchain
import (
"fmt"
mspclient "github.com/hyperledger/fabric-sdk-go/pkg/client/msp"
"github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt"
"github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/msp"
"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
"github.com/pkg/errors"
)
// FabricSetup implementation
type FabricSetup struct
ConfigFile string
OrgID string
OrdererID string
ChannelID string
ChainCodeID string
initialized bool
ChannelConfig string
ChaincodeGoPath string
ChaincodePath string
OrgAdmin string
OrgName string
UserName string
admin *resmgmt.Client
sdk *fabsdk.FabricSDK
// Initialize reads the configuration file and sets up the client, chain and event hub
func (setup *FabricSetup) Initialize() error
// Add parameters for the initialization
if setup.initialized
return errors.New("sdk already initialized")

// Initialize the SDK with the configuration file
sdk, err := fabsdk.New(config.FromFile(setup.ConfigFile))
if err != nil
return errors.WithMessage(err, "failed to create SDK")

setup.sdk = sdk
fmt.Println("SDK created")
// The resource management client is responsible for managing channels (create/update channel)
resourceManagerClientContext := setup.sdk.Context(fabsdk.WithUser(setup.OrgAdmin), fabsdk.WithOrg(setup.OrgName))
if err != nil
return errors.WithMessage(err, "failed to load Admin identity")

resMgmtClient, err := resmgmt.New(resourceManagerClientContext)
if err != nil
return errors.WithMessage(err, "failed to create channel management client from Admin identity")

setup.admin = resMgmtClient
fmt.Println("Ressource management client created")
// The MSP client allow us to retrieve user information from their identity, like its signing identity which we will need to save the channel
mspClient, err := mspclient.New(sdk.Context(), mspclient.WithOrg(setup.OrgName))
if err != nil
return errors.WithMessage(err, "failed to create MSP client")

adminIdentity, err := mspClient.GetSigningIdentity(setup.OrgAdmin)
if err != nil
return errors.WithMessage(err, "failed to get admin signing identity")

req := resmgmt.SaveChannelRequestChannelID: setup.ChannelID, ChannelConfigPath: setup.ChannelConfig, SigningIdentities: []msp.SigningIdentityadminIdentity
txID, err := setup.admin.SaveChannel(req, resmgmt.WithOrdererEndpoint(setup.OrdererID))
if err != nil || txID.TransactionID == ""
return errors.WithMessage(err, "failed to save channel")

fmt.Println("Channel created")
// Make admin user join the previously created channel
if err = setup.admin.JoinChannel(setup.ChannelID, resmgmt.WithRetry(retry.DefaultResMgmtOpts), resmgmt.WithOrdererEndpoint(setup.OrdererID)); err != nil
return errors.WithMessage(err, "failed to make admin join channel")

fmt.Println("Channel joined")
fmt.Println("Initialization Successful")
setup.initialized = true
return nil
func (setup *FabricSetup) CloseSDK()
setup.sdk.Close()

该文件可在此处获得: blockchain/setup.go
在这个阶段,只初始化了一个将与对等方、CA 和排序者通信的客户端。还创建了一个新频道并将这个对等点连接到这个频道。有关更多信息,请参阅代码中的注释。


3.3测试

为了确保客户端成功初始化了他的所有组件,我们将在启动网络的情况下进行一个简单的测试。为了做到这一点,我们需要构建 go 代码。由于我们没有任何主文件,我们必须添加一个:

cd $GOPATH/src/github.com/chainHero/heroes-service && \\
vi main.go

package main
import (
"fmt"
"github.com/chainHero/heroes-service/blockchain"
"os"
)
func main()
// Definition of the Fabric SDK properties
fSetup := blockchain.FabricSetup
// Network parameters
OrdererID: "orderer.hf.chainhero.io",
// Channel parameters
ChannelID: "chainhero",
ChannelConfig: os.Getenv("GOPATH") + "/src/github.com/chainHero/heroes-service/fixtures/artifacts/chainhero.channel.tx",
// Chaincode parameters
ChainCodeID: "heroes-service",
ChaincodeGoPath: os.Getenv("GOPATH"),
ChaincodePath: "github.com/chainHero/heroes-service/chaincode/",
OrgAdmin: "Admin",
OrgName: "org1",
ConfigFile: "config.yaml",
// User parameters
UserName: "User1",

// Initialization of the Fabric SDK from the previously set properties
err := fSetup.Initialize()
if err != nil
fmt.Printf("Unable to initialize the Fabric SDK: %v\\n", err)
return

// Close SDK
defer fSetup.CloseSDK()

该文件可在此处获得: main.go

使用如下命令确保安装依赖

go mod init

go mod vendor

待依赖下载完成后,即可开始编译

cd $GOPATH/src/github.com/chainHero/heroes-service && \\
go build

编译完成后会生成一个可执行的文件

输入命令

./heroes-service

此时就可看到


推荐阅读
  • intellij idea的安装与使用(保姆级教程)
    intellijidea的安装与使用(保姆级教程)IntelliJ在业界被公认为最好的java开发工具,尤其在智能代码助手、代码自动提示、重构、JavaEE支持、各类版本工具(gi ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 解决Cydia数据库错误:could not open file /var/lib/dpkg/status 的方法
    本文介绍了解决iOS系统中Cydia数据库错误的方法。通过使用苹果电脑上的Impactor工具和NewTerm软件,以及ifunbox工具和终端命令,可以解决该问题。具体步骤包括下载所需工具、连接手机到电脑、安装NewTerm、下载ifunbox并注册Dropbox账号、下载并解压lib.zip文件、将lib文件夹拖入Books文件夹中,并将lib文件夹拷贝到/var/目录下。以上方法适用于已经越狱且出现Cydia数据库错误的iPhone手机。 ... [详细]
  • 树莓派语音控制的配置方法和步骤
    本文介绍了在树莓派上实现语音控制的配置方法和步骤。首先感谢博主Eoman的帮助,文章参考了他的内容。树莓派的配置需要通过sudo raspi-config进行,然后使用Eoman的控制方法,即安装wiringPi库并编写控制引脚的脚本。具体的安装步骤和脚本编写方法在文章中详细介绍。 ... [详细]
  • 本文详细介绍了git常用命令及其操作方法,包括查看、添加、提交、删除、找回等操作,以及如何重置修改文件、抛弃工作区修改、将工作文件提交到本地暂存区、从版本库中删除文件等。同时还介绍了如何从暂存区恢复到工作文件、恢复最近一次提交过的状态,以及如何合并多个操作等。 ... [详细]
  • Week04面向对象设计与继承学习总结及作业要求
    本文总结了Week04面向对象设计与继承的重要知识点,包括对象、类、封装性、静态属性、静态方法、重载、继承和多态等。同时,还介绍了私有构造函数在类外部无法被调用、static不能访问非静态属性以及该类实例可以共享类里的static属性等内容。此外,还提到了作业要求,包括讲述一个在网上商城购物或在班级博客进行学习的故事,并使用Markdown的加粗标记和语句块标记标注关键名词和动词。最后,还提到了参考资料中关于UML类图如何绘制的范例。 ... [详细]
  • OpenCV4.5.0+contrib编译流程及解决错误方法
    本文介绍了OpenCV4.5.0+contrib的编译流程,并提供了解决常见错误的方法,包括下载失败和路径修改等。同时提供了相关参考链接。 ... [详细]
  • 本文探讨了容器技术在安全方面面临的挑战,并提出了相应的解决方案。多租户保护、用户访问控制、中毒的镜像、验证和加密、容器守护以及容器监控都是容器技术中需要关注的安全问题。通过在虚拟机中运行容器、限制特权升级、使用受信任的镜像库、进行验证和加密、限制容器守护进程的访问以及监控容器栈,可以提高容器技术的安全性。未来,随着容器技术的发展,还需解决诸如硬件支持、软件定义基础设施集成等挑战。 ... [详细]
  • 1.官网下载了mysql-5.7.17-win64.zip包,配置遇到很多麻烦,记录一下;2.解压后放到指定的文件夹,修改mysql-5.7.17的配置文件my-default.i ... [详细]
  • 大坑|左上角_pycharm连接服务器同步写代码(图文详细过程)
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了pycharm连接服务器同步写代码(图文详细过程)相关的知识,希望对你有一定的参考价值。pycharm连接服务 ... [详细]
  • 其实之前也有下载过完整的android源码,但是从来没有对这个做过一些总结,在加上最近需要经常去看,索性就在从新下载,编译一下,其实这些东西官网上面都有。http:sou ... [详细]
  • 1.脚本功能1)自动替换jar包中的配置文件。2)自动备份老版本的Jar包3)自动判断是初次启动还是更新服务2.脚本准备进入ho ... [详细]
  • Jmeter对RabbitMQ压力测试
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Jmeter对RabbitMQ压力测试相关的知识,希望对你有一定的参考价值。Jm ... [详细]
  • 现在比较流行使用静态网站生成器来搭建网站,博客产品着陆页微信转发页面等。但每次都需要对服务器进行配置,也是一个重复但繁琐的工作。使用DockerWeb,只需5分钟就能搭建一个基于D ... [详细]
  • Ansibleplaybook roles安装redis实例(学习笔记二十九)
    1、相关redis参数:2、templatesredis.conf配置相关参数:daemonizeyespidfilevarrunredis_{{red ... [详细]
author-avatar
丹愿人常久6688
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有